<template>
  <div>
    <!-- 表格操作项 start  -->
    <template v-for="(item, index) in tableBtn">
      <Button
        v-if="showBtn(item.label)"
        :key="index"
        type="primary"
        :icon="item.icon"
        class="ivu-mr-8"
        :loading="exportLoading"
        @click="tableTopOperate(item.name)"
        >{{ item.label }}</Button
      >
    </template>
    <Dropdown
      class="ivu-ml-8"
      v-show="tableSelectData && tableSelectData.length > 0"
      @on-click="handleClickItem"
    >
      <Button
        >更多操作
        <Icon type="ios-arrow-down" />
      </Button>
      <DropdownMenu slot="list">
        <template v-for="(item, index) in tableBatchBtns">
          <DropdownItem
            :key="index"
            :name="item.name"
            v-if="showBtn(item.label)"
            >{{ item.label }}
          </DropdownItem>
        </template>
      </DropdownMenu>
    </Dropdown>
    <Modal
      @on-ok="handleSubmit('formData')"
      title="新增属性值"
      :loading="loading"
      v-model="shipmentsFlag"
    >
      <div style="width: 60%; margin: 0 auto">
        <Form :model="formLeft" label-position="left" :label-width="100">
          <FormItem label="属性类型">
            <Select disabled v-model="model1" style="width: 200px">
              <Option
                v-for="item in retData"
                :value="item.attributeType"
                :key="item.attributeType"
              >
                {{ item.attributeZn }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="属性名称">
            <Input
              v-model="formLeft.input1"
              show-word-limit
              maxlength="30"
            ></Input>
          </FormItem>
          <FormItem label="属性别名">
            <Input
              v-model="formLeft.input4"
              show-word-limit
              maxlength="30"
            ></Input>
          </FormItem>
          <!-- <FormItem label="">
            <Button type="primary" :loading="sLoading"  @click="handleSubmit('formData')">保存</Button>
            <Button style="margin-left: 8px"  @click="cancel">取消</Button>
          </FormItem>   -->
        </Form>
      </div>
      <div slot="footer">
        <Button
          type="primary"
          :loading="sLoading"
          @click="handleSubmit('formData')"
          >保存</Button
        >
        <Button style="margin-left: 8px" @click="modalClose()">取消</Button>
      </div>
    </Modal>
    <!-- 表格操作项 end  -->
    <Modal v-model="modal1" title="关联属性" width="70%" height="50%">
      <div class="conter">
        <p class="left">
          <span class="name">属性名称</span
          ><Input v-model="attributeName" placeholder="" style="width: 150px" />
        </p>
        <p class="right">
          <span class="name">英文名称</span
          ><Input v-model="engName" placeholder="" style="width: 150px" />
        </p>
        <Button type="primary" class="btn" @click="query">查询</Button>
        <Button type="primary" class="btn1" @click="resetting">清空</Button>
      </div>
      <div class="conter button">
        <Button type="primary" class="btn" @click="relevance()"
          >批量关联</Button
        >
        <Button type="primary" class="btn" @click="addAttribute()"
          >新增属性</Button
        >
      </div>

      <Table
        border
        ref="selection"
        :columns="columns4"
        :data="data1"
        @on-select="handleSelect"
        @on-select-all="handleSelect1"
      >
        <template slot-scope="{ row, index }" slot="action">
          <Button
            type="primary"
            size="small"
            style="margin-right: 5px"
            @click="show(row, index)"
            >关联</Button
          >
        </template>
      </Table>
      <!-- 分页 start  -->
      <div class="ivu-mt ivu-text-center">
        <Page
          :total="NoRelAttributeTotalNum"
          transfer
          show-total
          show-sizer
          :current.sync="NoRelAttributeNowPage"
          @on-change="getNoRelAttributeList"
          @on-page-size-change="NoRelAttributeChangePage"
        />
      </div>
      <!-- 分页 end  -->
      <!-- 调用表格子组件 end  -->
      <div slot="footer"></div>
    </Modal>
    <BatchImportDialog
      :visible.sync="batchImport.visible"
      :dialogTitle="batchImport.dialogTitle"
      :contents="batchImport.contents"
      :actionUrl="batchImport.actionUrl"
    />
  </div>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import dynamictablebtns from '@/mixins/dynamictablebtns'; // 混入通用代码
import { mapGetters, mapState } from 'vuex';
import { createExcelByExport } from '@/utils/bizUtils'
import BatchImportDialog from '@/components/BatchImportDialog';
export default {
  mixins: [dynamictablebtns],
  components: {
    BatchImportDialog
  },
  data () {
    return {
      batchImport: {
        visible: false,
        dialogTitle: '批量导入属性',
        contents: [
          '线下整理好需导入的表格。',
          '表格格式：模板编号  模板名称  属性编号  属性名称  是否规格  是否必填  属性类型  位置 ',
          '导入表格从第二行开始导入，第一行为表头不导入。',
          '提交后页面关闭，系统后台更新数据，根据数据量大小更新时间不同。',
          '每次导入的限制为1000。',
        ],
        actionUrl: '/sysback/template/producttemplateandattrrel/importTemplateAttrRel'
      },
      exportLoading: false,
      loading: true,
      uuids: [], // 批量关联id
      row: '',
      page: '',
      attributeName: '',
      engName: '',
      sLoading: false,
      modal1: false,
      shipmentsFlag: false, // 新增属性
      columns4: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '属性名称',
          key: 'attributeName'
        },
        {
          title: '英文名称',
          key: 'engName'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ],
      data1: [],
      NoRelAttributeLoading: true,
      NoRelAttributeListData: [],
      NoRelAttributeTotalNum: 0,
      NoRelAttributeNowPage: 1,
      NoRelAttributePageShow: 10,
      cityList: [],
      retData: [],
      model1: '01',
      model2: '',
      model3: '',
      formLeft: {
        input1: '',
        input4: '',
        desc: ''
      }
    };
  },
  // created () {
  //   this.getAttributeTypeList();
  // },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    ...mapState('admin/baseList', [
      'searchFormData',
    ]),
  },
  methods: {
    modalClose () {
      this.shipmentsFlag = false;
    },
    getAttributeTypeList () {
      ApiRequest(
        '/sysback/template/producttemplateattr/getAttributeTypeList',
        'post'
      ).then(res => {
        this.retData = res.retData;
      });
    },
    handleSubmit (name) {
      // 新增属性模板
      let data = {};
      if (this.model1 === '') {
        this.$Message.error('请选择属性');
        this.shipmentsFlag = true;
        return;
      }
      if (this.model1 === '01') {
        if (this.formLeft.input1 === '') {
          this.$Message.error('请输入属性名称');
          this.shipmentsFlag = true;
          return;
        }
        if (this.formLeft.input4 === '') {
          this.$Message.error('请输入属性别名');
          this.shipmentsFlag = true;
          return;
        }
        data = {
          attributeName: this.formLeft.input1,
          aliasAttrName: this.formLeft.input4,
          engName: '',
          unit: '',
          attributeType: '01',
          templateUuid: this.$route.query.uuid
          // type: this.formData.type
        };
      }
      if (this.sLoading) {
        return false;
      }
      this.sLoading = true;
      // 开始请求会员信息
      ApiRequest(
        '/sysback/template/producttemplateattr/createAndRelTemplateAttr',
        'post',
        data
      ).then(res => {
        if (res.retStatus === '1') {
          this.$Message.success('成功!');
          this.getNoRelAttributeList();
          this.actionsChange();
          this.modal1 = true;
          // this.$router.go(-1)
          this.shipmentsFlag = false;
        } else {
          this.shipmentsFlag = true;
        }

        this.sLoading = false;
      });
    },
    // 全部属性切换分页
    NoRelAttributeChangePage (val) {
      this.NoRelAttributePageShow = val;
      this.$nextTick(() => {
        this.getNoRelAttributeList();
      });
    },
    // 查询
    query () {
      this.getNoRelAttributeList();
    },
    // 清空
    resetting () {
      this.attributeName = '';
      this.engName = '';
      this.getNoRelAttributeList();
    },
    // 获取属性列表
    getNoRelAttributeList () {
      let uuid = this.$route.query.uuid;
      this.modal1 = true;
      let searchParam = [];

      searchParam.push({ name: 'attributeName', value: this.attributeName });
      searchParam.push({ name: 'attributeName_q', value: 'Like' });
      searchParam.push({ name: 'engName', value: this.engName });
      searchParam.push({ name: 'engName_q', value: 'Like' });
      searchParam.push({ name: 'templateUuid', value: uuid });
      searchParam.push({ name: 'templateUuid_q', value: 'EQ' });

      let data = {
        nowPage: this.NoRelAttributeNowPage,
        pageShow: this.NoRelAttributePageShow,
        searchParam: JSON.stringify(searchParam),
        sortName: '',
        sortType: ''
      };

      // 开始请求列表
      ApiRequest(
        this.requestApi.relevanceList.url,
        this.requestApi.relevanceList.type,
        data
      ).then(res => {
        this.NoRelAttributeTotalNum = res.retData.totalNum;
        this.data1 = res.retData.results;
      });
    },
    addAttribute () {
      // 新增属性
      this.shipmentsFlag = true;
    },
    // 表格操作项事件
    tableTopOperate (name) {
      if (name === 'export') {
        this.exportLoading = true;
        ApiRequestExportTable(
          '/sysback/template/producttemplateandattrrel/exportTemplateAttrRel',
          'post',
          this.searchFormData,
          false
        )
          .then((res) => {
            this.exportLoading = false;
            createExcelByExport({ res, excelTitle: '属性模板' })
          })
          .catch(() => {
            this.exportLoading = false;
            this.$message.error('导出失败');
          });
        // this.$emit('exportData');
      } else if (name === 'add') {
        let jumpPath = this.jumpPath + 'Add';
        this.$router.push({ path: jumpPath });
      } else if (name === 'associationProperty') {
        this.getNoRelAttributeList();
      } else if (name === 'templateCheckSubmit') {
        if (this.tableSelectData.length == 0) {
          this.$Message.error('请选择');
          return;
        }
        this.handleClickItem('templateCheckSubmit');
      } else if (name === 'templateCheckClose') {
        this.$router.push({ name: 'templateList' });
      } else if (name == 'batchImport') {
        this.batchImport.visible = true
      }
    },
    handleSelect (row) {
      this.row = row;
    },
    handleSelect1 (row) {
      this.row = row;
    },
    relevance () {
      this.uuids = [];
      this.row.forEach(item => {
        this.uuids.push(item.uuid);
      });
      this.$Modal.confirm({
        title: '批量关联',
        content: '确定要批量关联选中的吗？',
        onOk: () => {
          let uuid = this.$route.query.uuid;
          let data = {
            attributeUuids: this.uuids.join(','),
            templateUuid: uuid
          };
          // 开始请求列表
          ApiRequest(
            this.requestApi.relevance.url,
            this.requestApi.relevance.type,
            data,
            true
          ).then(res => {
            if (res.retStatus === '1') {
              this.$Message.success('关联成功');
              this.getNoRelAttributeList();
              this.actionsChange();
            }
          });
        }
      });
    },
    show (row, index) {
      this.$Modal.confirm({
        title: '关联',
        content: '确定要关联选中的吗？',
        onOk: () => {
          let uuid = this.$route.query.uuid;
          let data = {
            attributeUuids: row.uuid,
            templateUuid: uuid
          };
          // 开始请求列表
          ApiRequest(
            this.requestApi.relevance.url,
            this.requestApi.relevance.type,
            data,
            true
          ).then(res => {
            if (res.retStatus === '1') {
              this.$Message.success('关联成功');
              this.getNoRelAttributeList();
              this.actionsChange();
            }
          });
        }
      });
    },
    handleSelectAll (status) {
      this.$refs.selection.selectAll(status);
    },
    ok () {
      this.$Message.info('Clicked ok');
    },
    // table 操作列点击事件
    handleClickItem (name) {
      let that = this;
      if (name === 'delete') {
        let uuidArr = [];
        that.tableSelectData.forEach(item => {
          uuidArr.push(item.uuid);
        });
        that.$Modal.confirm({
          title: '批量删除',
          content: '确定要删除这些数据吗？',
          onOk: () => {
            let data = {
              uuids: uuidArr.join(',')
            };
            // 开始请求列表
            ApiRequest(
              that.requestApi.batchDelTableList.url,
              that.requestApi.batchDelTableList.type,
              data,
              true
            ).then(res => {
              if (res.retStatus === '1') {
                this.$Message.success('批量删除成功');
                this.tableSelectData = [];
                this.actionsChange();
              }
            });
          }
        });
      } else if (name === 'templateCheckSubmit') {
        let paramList = [];
        that.tableSelectData.forEach(item => {
          paramList.push(item);
        });
        that.$Modal.confirm({
          title: '批量更新',
          content: '确定要批量更新吗？',
          onOk: () => {
            let data = {
              paramList: paramList
            };
            // 开始请求列表
            ApiRequest(
              that.requestApi.renewTableList.url,
              that.requestApi.renewTableList.type,
              data,
              false
            ).then(res => {
              if (res.retStatus == 1) {
                this.$Message.success('更新成功');
                this.tableSelectData = [];
                this.$parent.handleClearSelect && this.$parent.handleClearSelect()
                this.actionsChange();
              } else {
                this.$Message.error(res.retMessage);
              }
            });
          }
        });
      } else if (name === 'disassociation') {
        that.$Modal.confirm({
          title: '批量取消关联',
          content: '确定要取消选中的关联吗？',
          onOk: () => {
            let uuid = that.$route.query.uuid;
            let uuidArr = [];
            that.tableSelectData.forEach(item => {
              uuidArr.push(item.uuid);
            });
            let data = {
              needDeleteUuids: uuidArr.join(','),
              templateUuid: uuid
            };

            // 开始请求列表
            ApiRequest(
              that.requestApi.disassociationTableList.url,
              that.requestApi.disassociationTableList.type,
              data,
              true
            ).then(res => {
              if (res.retStatus === '1') {
                that.$Message.success('取消关联成功');
                that.tableSelectData = [];
                this.$parent.handleClearSelect && this.$parent.handleClearSelect()
                this.actionsChange();
                /* //that.actionsChange()
                                    that.$router.go(0); */
              }
            });
          }
        });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.button {
  margin-left: 4%;
  margin-bottom: 1%;
}

.left {
  float: left;
  width: 40%;
  margin-bottom: 2%;
}

.right {
  float: left;
  width: 40%;
  margin-bottom: 2%;
}

.name {
  margin-right: 3%;
}

.modal {
  width: 50%;
  height: 50%;
}

.btn {
  float: left;
  margin-left: 2%;
}

.btn1 {
  float: left;
  margin-left: 2%;
  font-size: 14px;
  color: #666666;
  background-color: #fff;
}

.conter {
  width: 100%;
  overflow: hidden;
}
</style>
